<template>
  <div class="select-user-page">
    <!-- 自动补全搜索框 -->
    <div class="search-section">
      <el-autocomplete
          class="search-input"
          v-model="searchContent"
          :fetch-suggestions="querySearchAsync"
          placeholder="请输入用户名/账户"
          @select="handleSelect"
          :highlight-first-item="true"
      />
      <van-button icon="search" type="primary" size="small" class="search-btn" @click="onSearchBtn"/>
    </div>

    <!-- 搜索结果区域 -->
    <div class="search-results-section">
      <div v-if="searchResults.length > 0" class="results-list">
        <van-card 
          v-for="user in searchResults" 
          :key="user.id"
          :price="user.planetCode"
          :desc="user.personalProfile"
          :title="`${user.username}<${user.planetCode}>`"
          :thumb="user.avatarUrl"
          currency="⭐️"
          :tag="user.gender === 0 ? '♂' : ' ♀ '"
          @click="handleUserClick(user)"
        >
          <template #tags>
            <van-tag type="success" plain v-for="tag in user.tags" :key="tag" class="user-tag">
              {{ tag }}
            </van-tag>
          </template>
          <template #footer>
            <van-button size="mini" @click.stop="handleUserClick(user)">联系我</van-button>
          </template>
        </van-card>
      </div>
      <div v-else class="empty-state">
        <van-empty description="暂无数据" />
      </div>
    </div>

    <!-- 智能推荐部分 -->
    <div class="recommend-section">
      <div class="section-title">智能推荐</div>
      <div v-if="recommendUsers.length > 0" class="recommend-list">
        <van-card 
          v-for="user in recommendUsers" 
          :key="user.id"
          :price="user.planetCode"
          :desc="user.personalProfile"
          :title="`${user.username}<${user.planetCode}>`"
          :thumb="user.avatarUrl"
          currency="⭐️"
          :tag="user.gender === 0 ? '♂' : ' ♀ '"
          @click="handleUserClick(user)"
        >
          <template #tags>
            <van-tag type="success" plain v-for="tag in user.tags" :key="tag" class="user-tag">
              {{ tag }}
            </van-tag>
          </template>
          <template #footer>
            <van-button size="mini" @click.stop="handleUserClick(user)">联系我</van-button>
          </template>
        </van-card>
      </div>
      <div v-else class="loading-state">
        <van-loading type="spinner" size="24px">加载中...</van-loading>
      </div>
    </div>
  </div>
</template>


<script setup lang="ts">

//button组件相关信息,查找匹配用户
import {useRouter} from "vue-router";
import {ref, onMounted} from "vue";
import {searchStore} from "../stores/search/search";
import {showToast} from "vant";
import {userStore} from "../stores/user/user";
import {getESUserByAll} from "../api/esApi";
import {selectUserById, getRecommend} from "../api/userApi";

const router = useRouter();
const searchStoreAPI = searchStore();
const userStoreAPI = userStore();
const searchContent = ref('');
const tipData = ref([]);
const searchResults = ref<any[]>([]);
const recommendUsers = ref<any[]>([]);
//查询请求自动补全功能
const querySearchAsync = async (queryString: string, cb: (arg: any) => void) => {
  //可以拿到输入的数据queryString
  console.log('query', queryString);
  //请求接口！拿数据
  const res = await getESUserByAll(queryString);

  if (200 === res.code) {
    tipData.value = res.data;
    // 处理标签数据
    if (res.data && res.data.length > 0) {
      res.data.forEach((user: any) => {
        if (user.tags && typeof user.tags === 'string') {
          try {
            user.tags = JSON.parse(user.tags);
          } catch (e) {
            user.tags = [];
          }
        }
      });
    }
    cb(res.data)//自动补全
  }

}
//选中某个item的方法=》跳转
const handleSelect = async (item: typeof modelValue | any) => {
  const res = await selectUserById(item.id);
  if (200 === res.code) {
    userStoreAPI.setOtherUserInfo(res.data);
    await router.push({
      path: '/userInfo',
    });
    return;
  }
  showToast('异常');
}

//点击按钮搜索
const onSearchBtn = () => {
  if (searchContent.value == '') {
    showToast("请输入账户在搜索");
    return;
  }
  //检测是否有匹配的
  if (tipData.value == null || tipData.value.length == 0) {
    showToast("没有匹配的用户");
    searchResults.value = [];
    return;
  }

  // 更新搜索结果
  searchResults.value = tipData.value.map((user: any) => {
    if (user.tags && typeof user.tags === 'string') {
      try {
        user.tags = JSON.parse(user.tags);
      } catch (e) {
        user.tags = [];
      }
    }
    return user;
  });

  // 保留原有的跳转逻辑（如果需要）
  searchStoreAPI.setSearchTipData(tipData.value);
};

// 处理用户点击
const handleUserClick = async (user: any) => {
  const res = await selectUserById(user.id);
  if (200 === res.code) {
    userStoreAPI.setOtherUserInfo(res.data);
    await router.push({
      path: '/userInfo',
    });
    return;
  }
  showToast('异常');
};

// 加载推荐用户
const loadRecommendUsers = async () => {
  try {
    const res = await getRecommend("1", "3");
    if (res.code === 200) {
      recommendUsers.value = res.data.map((user: any) => {
        if (user.tags && typeof user.tags === 'string') {
          try {
            user.tags = JSON.parse(user.tags);
          } catch (e) {
            user.tags = [];
          }
        }
        return user;
      });
    }
  } catch (error) {
    console.log(error);
  }
};

// 页面加载时获取推荐用户
onMounted(() => {
  loadRecommendUsers();
});


</script>


<style scoped>
.select-user-page {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 20px;
}

/* 搜索区域 */
.search-section {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px;
  background-color: #fff;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.search-input {
  width: 75%;
  flex: 1;
}

.search-btn {
  margin-left: 8px;
}

/* 搜索结果区域 */
.search-results-section {
  margin: 16px;
  min-height: 200px;
}

.results-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.empty-state {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 200px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.user-tag {
  margin-right: 8px;
  margin-top: 4px;
}

/* 智能推荐区域 */
.recommend-section {
  margin: 16px;
  padding: 16px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #323233;
  margin-bottom: 12px;
  padding-bottom: 8px;
  border-bottom: 1px solid #ebedf0;
}

.recommend-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 40px 0;
}
</style>